<template>
    <MenuPage 
          :data="expGuideList" 
          :columns="guideCol"
          :page.sync="expGuidePage"
          :size.sync="expGuidePageSize"
          :total="expGuideTotal"
          :loading="guideLoading"
          :showtitle="$route.name==='guide'"
          @queryFun="getGuideList">
          <template slot="search">
    
    <!--          <Divider type="vertical" style="margin: 10px 0px 10px 10px;" />-->
              <div style="height: 32px;line-height: 32px;margin-left: 15px">
                <Checkbox v-model="creatByMeModal" @on-change="searchCreatedByMe" style="width: 70px;"
                  >由我创建</Checkbox
                >
              </div>
              <i-select
                clearable
                placeholder="可见范围"
                style="width: 150px;margin-left:15px; "
                v-model="ispublic"
                @on-change="searchGuideBtn"
              >
                <i-option value="2">系统</i-option>
                <i-option value="1">单位</i-option>
                <i-option value="0">个人</i-option>
              </i-select>
              <Input
                v-model.trim="searchGuideInput"
                placeholder="指导书名称"
                clearable
                @on-change="searchGuideBtn"
                style="width: 180px;margin-left:15px;"
              />
              <Button
                  type="primary"
                  ghost
                  class="md-add-jh"
                  style="margin-right: 5px"
                  @click="addGuideModal"
              ><i class="el-icon-edit"></i>创建</Button
              >
              <Button ghost style="margin-right: 5px" type="primary" icon="ios-cloud-download-outline"
              ><a
                  href="static/guidebook_template.docx"
                  download="guidebook_template.docx"
                  class="downloadUrl"
              >下载{{pageBtnTxt}}模板</a
              ></Button
              >
              <Button
                  type="primary"
                  ghost
                  icon="ios-cloud-upload-outline"
                  @click="importGuide"
                  style="margin-right:5px"
              >导入{{ pageBtnTxt }}</Button>
              <Button
                class="header-btn"
                type="primary"
                ghost
                style="height: 32px;margin-left: 5px;"
                @click="refreshFile()"
                ><i class="el-icon-refresh-right"
              /></Button>
          </template>
  </div>
    <!-- 创建修改指导书 -->
    <Modal
      v-model="createGuideModal"
      width="450"
      :mask-closable="false"
      :footer-hide="true"
      :title="guideTitle"
    >

<!--      cancel-text="重置"-->
<!--      @on-ok="submitBtn('examinationformValidate')"-->
<!--      @on-cancel="creatGuideHandleReset('examinationformValidate')"-->
      
      <Form
        ref="creatGuideFormValidate"
        :model="creatGuideFormValidate"
        :rules="creatGuideRuleValidate"
        :label-width="80"
   
      >
        <FormItem label="名称" prop="name">
          <Input
              maxlength="128"
            v-model.trim="creatGuideFormValidate.name"
            placeholder='名称不能包含英文字符 \ / : * ? " < > | 等特殊字符'
          ></Input>
        </FormItem>
        <FormItem label="可见范围" prop="ispublic">
          <RadioGroup v-model="creatGuideFormValidate.ispublic">
            <Radio label="1">单位</Radio>
            <Radio label="0">个人</Radio>
          </RadioGroup>
          <Tooltip
            v-if="!isCreate"
            style="margin-left: 10px;"
            :transfer="true"
            max-width="200"
            content="可见范围由个人修改为单位时，指导书使用的个人资源(图片，题目)的可见范围将变为单位"
            placement="top"
          >
            <Icon type="ios-alert" class="ios-alert" />
          </Tooltip>
        </FormItem>
        <FormItem class="ivu-modal-footer custom-modal-footer">
          <Button @click="creatGuideHandleReset('creatGuideFormValidate')" style="margin-left: 8px"
          >重置</Button>
          <Button type="primary" @click="submitBtn('creatGuideFormValidate')">确定</Button>

        </FormItem>
      </Form>
    </Modal>
    <!-- 查看指导书 -->
    <Modal
      v-model="bookInfoModal"
      :mask-closable="false"
      :footer-hide="true"
      :title="guideName"
      :width="1200"
    >
      <div v-show="showSection">
        <div v-if="isMd && sectionData[0]" style="max-height: calc(100vh - 190px);overflow-y: auto;">
          <mavon-editor
            v-model="sectionData[0].sectiontext"
            :subfield="false"
            :toolbarsFlag="false"
            :ishljs="true"
            :code_style="code_style"
            :externalLink="externalLink"
            defaultOpen="preview"
          />
        </div>
        <section v-else>
          <SectionList :data="sectionData"></SectionList>
        </section>
      </div>
      <div style="width: 100%;">
        <div v-show="showDefImg1" class="defGraphWrap">
          <div class="defGraph"></div>
          <div class="graphText">暂无段落</div>
        </div>
      </div>
    </Modal>
    <!--上传文件-->
    <Modal
      v-model="importGuideModal"
      :mask-closable="false"
      width="500"
      :closable="false"
      :footer-hide="true"
      :title="`导入${pageBtnTxt}`"
    >
      <Form
        ref="formItem"
        :model="importGuideFormValidate"
        :rules="importGuideRuleValidate"
        :label-width="80"
      >
        <FormItem label="上传文件" prop="file">
          <Upload
            v-model="importGuideFormValidate.file"
            :action="upLoadUrl"
            :before-upload="handleUploadIcon"
          >
            <Button icon="ios-cloud-upload-outline" :disabled="loading">选择文件</Button>
          </Upload>
          <Poptip
            class="too"
            popper-class="tooltipclass"
            theme="dark"
            placement="top"
            width="400"
            :transfer="true"
            trigger="hover"
          >
            <Icon type="ios-alert" class="ios-alert" />
            <div class="api" slot="content">
              <p>支持上传类型：doc,docx,md</p>
              <!-- <p>文件大小不能超过20M</p> -->
              <p style="white-space: normal;">
                指导书标题不能包含英文字符 \ / : * ? " < > |等字符，长度为1-128个字符
              </p>
              <p>不支持gif等动图导入</p>
              <p style="white-space: normal;">
                导入的指导书文档中的段落标题必须使用一级标题或二级标题，否则将不会作为指导书章节处理，不属于章节的内容导入时可能会丢失
              </p>
            </div>
          </Poptip>
          <div v-if="importGuideFormValidate.file">
            <p>文件名: {{ importGuideFormValidate.file.name }}</p>
            <p>大小：<span v-text="fileSize"></span></p>
            <Progress :percent="progress"></Progress>
            <p>速度：<span v-text="speed"></span></p>
          </div>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="formBtn('formItem')" :loading="loading">确定</Button>
          <Button @click="cancelUpload()" style="margin-left: 8px">取消</Button>
        </FormItem>
      </Form>
    </Modal>
</MenuPage>
</template>
<script>
import $ from 'jquery';
import encryption from '@/libs/encryption.js';
import {
  getGuideData,
  exportGuide,
  creatGuide,
  modifyGuide,
  delGuide,
  sectionList,
  querySectionQuestion
} from '@/api/guide.js';
import { wordExport } from './html-to-word/wordexport.js';
import { escape2Html } from '@/libs/utils';
import { debounce } from '@/libs/utils';
import pageTitle from '@/mixin/pageTitle';
import { newValidationRules ,newValidationRulesTip} from '@/libs/reg.js'
import QuestionCard from '@/components/question-list/question-card.vue';
import { mapState } from 'vuex'
import SectionList from '@/components/common/guide-section-list'
export default {
  mixins: [pageTitle],
  components: {QuestionCard,SectionList},
  data() {
    //      	const validateName = (rule, value, callback) => {
    //		      	var reg = new RegExp("^[\u4E00-\u9FA5a-zA-Z0-9_ -.]*$");
    //		      	//验证警戒值
    //		      	if(value){
    //		      		if (!reg.test(value)) {
    //		      			callback(new Error('请输入中文、英文、数字、下划线、点(.)、-'));
    //		      		}else{
    //		      			callback()
    //		      		}
    //		      	}else{
    //		      		callback()
    //		      	}
    //		    }
    const validateName = (rule, value, callback) => {
      // var reg = /[\\\:：*?？"”<>|;；，,+=]/gi;
      var reg = newValidationRules;
      //验证警戒值
      if (value) {
        if (reg.test(value)) {
          callback(new Error(newValidationRulesTip('',128)));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    const validateUpload = (rule, value, callback) => {
      if (!this.importGuideFormValidate.file) {
        callback(new Error('请选择上传的文件'));
      } else {
        callback();
      }
    };
    return {
      // 用户信息
      USER_ID: '',
      isRootDesigner: '',
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      setTableHei: 'auto',
      // 显示
      showDataList: true,
      showDefImg: false,
      //md指导书
      isMd: false,
      code_style: 'solarized-dark',
      externalLink: {
        markdown_css: function() {
          // 这是你的markdown css文件路径
          return `/bdesigner/markdown/github-markdown.min.css`;
        },
        hljs_js: function() {
          // 这是你的hljs文件路径
          return `/bdesigner/highlightjs/highlight.min.js`;
        },
        hljs_css: function(css) {
          // 这是你的代码高亮配色文件路径
          return `/bdesigner/highlightjs/styles/${css}.min.css`;
        },
        hljs_lang: function(lang) {
          // 这是你的代码高亮语言解析路径
          return `/bdesigner/highlightjs/languages/${lang}.min.js`;
        },
        katex_css: function() {
          // 这是你的katex配色方案路径路径
          return `/bdesigner/katex/katex.min.css`;
        },
        katex_js: function() {
          // 这是你的katex.js路径
          return `/bdesigner/katex/katex.min.js`;
        }
      },
      // 说明指导书
      guideLoading: false,
      expGuideList: [],
      guideCol: [
          {
              type:'link',
              title: '名称',
              key: 'guidbookname',
              align: 'left',
              on:{
                click:(data) => {
                  this.showBookInfo(data)
                }
              }
          },
          {
              title: '可见范围',
              key: 'ispublic',
              align: 'left',
              render: (h, params) => {
                  return h(
                      'div',
                      {
                          style: {
                              color: this.setVisibility(params.row.ispublic).color
                          }
                      },
                      this.setVisibility(params.row.ispublic).text
                  );
              }
          },
          {
              title: '已使用',
              key: 'expUsed',
              align: 'left',
              filter:(expUsed) => {
                return expUsed ? '是' : '否'
              },
              setColor:(expUsed) => {
                return expUsed ? 'var(--status-yes)' : 'var(--status-no)'
              }
          },
          {
              title: 'md格式',
              key: 'templateid',
              align: 'left',
              filter:(templateid) => {
                return templateid == 'markdown' ? '是' : '否'
              },
              setColor:(templateid) => {
                return templateid && templateid == 'markdown' ? 'var(--status-yes)' : 'var(--status-no)'
              }
          },
          {
              title: '创建者',
              key: 'createuser',
              align: 'left'
          },
          {
              title: '更新时间',
              key: 'updatetime',
              align: 'left',
              minWidth:150,
          },
          {
            title: '操作',
            key: 'action',
            width:240,
            opList:[
              {
                txt:(data) => {
                  return data.templateid == 'markdown' ? '文档编辑' : '段落管理' 
                },
                disabled:this.setBtnType,
                on:{
                  click:(data,e) => {
                    this.goSection(data)
                  }
                }
              },
              {
                txt:'下载',
                disabled:this.setDownloadIsClick,
                on:{
                  click:(data,e) => {
                    this.htmlToWord(data)
                  }
                }
              },
              {
                txt:'修改',
                disabled:this.setModifyIsClick,
                on: {
                  click: (data,e) => {
                    this.madifyGuide(data);
                  }
                }
              },
              {
                txt: '删除',
                tooltip: true,
                type: 'delete',
                title: '确定要删除这个文件吗？',
                disabled: (data) => {
                  return this.setIsClick(data) ? true :false
                },
                on: {
                  click: (data,e) => {
                    this.delGuide(data)
                  }
                }
              }
            ]
        }
      ],
      expGuidePage: 1,
      expGuidePageSize: 12,
      ispublic: '',
      expGuideTotal: 0,
      searchGuideInput: '',
      shareStatus: 'all',
      creatByMeModal: false,
      // 是新建还是修改
      isCreate: true,
      guideTitle: '',
      // 创建指导书
      createGuideModal: false,
      creatGuideFormValidate: {
        name: '',
        ispublic: '1'
      },
      creatGuideRuleValidate: {
        name: [
          { required: true, max: 128, message: '指导书名称长度为1—128个字符', trigger: 'change' },
          { validator: validateName, trigger: 'change' }
        ],
        ispublic: [{ required: true, message: 'Please select ispublic', trigger: 'change' }]
      },
      // 修改指导书
      reGuideId: '',
      // 段落数据
      sectionData: [],
      bookInfoModal: false,
      guideName: '',
      showCloseAndOpenBtn: true,
      closeIconSrc: require('../../assets/exper/close-grey.png'),
      openIconSrc: require('../../assets/exper/open-grey.png'),
      downLoadImg: require('../../assets/project/download-h.png'),
      downLoadDImg: require('../../assets/project/download-s.png'),
      showDefImg1: false,
      showSection: false,
      //导入指导书
      importGuideModal: false,
      importGuideFormValidate: {
        file: null
      },
      importGuideRuleValidate: {
        file: [{ required: true, validator: validateUpload, trigger: 'change' }]
      },
      upLoadUrl: `${this.baseURL}/self-study/guide/expGuide/generateExpGuideByWord`,
      formatArr: ['doc', 'docx', 'md'],
      speed: 0,
      loaded: 0,
      progress: 0,
      fileSize: 0,
      loading: false,
      a: 0
    };
  },
  computed:{
    
  },
  created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
  },
  mounted() {
    //赋值查询条件
    let queryObj = sessionStorage.getItem('queryObj');
    if (queryObj) {
      let params = JSON.parse(queryObj);
      this.expGuidePage = params.page;
      this.expGuidePageSize = params.rows;
      this.ispublic = params.ispublic;
      this.searchGuideInput = params.guidbookname;
      this.creatByMeModal = params.designer == this.USER_ID ? true : false;
      sessionStorage.removeItem('queryObj');
    }
    // this.setStyle();
    // window.onresize = () => {
    //   this.setStyle();
    // };
    //          let getPage = this.$route.query.page?parseInt(this.$route.query.page):1
    //          this.expGuidePage = getPage
    // 指导书列表
    this.getGuideList();
  },
  watch: {
    createGuideModal(type) {
      // 模态框隐藏，重置表单
      if (!type) {
        this.$refs.creatGuideFormValidate.resetFields();
      }
    }
  },
  methods: {
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.setTableHei = this.fullHeight - 197;
      this.expGuidePageSize = Math.floor(this.setTableHei / 96);
    },
    // 指导书列表
    getGuideList() {
      this.showDataList = false;
      this.showDefImg = true;
      let params = {
        page: this.expGuidePage,
        rows: this.expGuidePageSize,
        order: 'desc',
        sortBy: 'createtime'
      };
      if (this.ispublic) {
        params.ispublic = this.ispublic;
      }
      if ($.trim(this.searchGuideInput) != '') {
        params.guidbookname = this.searchGuideInput;
      }
      if (this.creatByMeModal) {
        params.designer = this.USER_ID;
      }
      this.queryObj = JSON.stringify(params);
      this.guideLoading = true;
      getGuideData(params)
        .then((data) => {
          if (data.code == 1) {
            let attribute = data.attribute;
            let items = attribute.dataList;
            this.expGuideTotal = attribute.totalCount;
            this.expGuideList = items;
            if (items.length > 0) {
              this.showDataList = true;
              this.showDefImg = false;
            } else {
              this.showDataList = false;
              this.showDefImg = true;
            }
          } else {
            this.showDataList = false;
            this.showDefImg = true;
          }
          this.guideLoading = false;
        })
        .catch((err) => {
          console.log(err);
          this.guideLoading = false;
          this.showDataList = false;
          this.showDefImg = true;
        });
    },
    guideOnChange(val) {
      this.expGuidePage = val;
      this.getGuideList();
    },
    changeType(val) {
      this.expGuidePage = 1;
      //              this.creatByMeModal = false
      this.shareStatus = val;
      this.getGuideList();
    },
    searchGuideBtn() {
      this.expGuidePage = 1;
      //              this.creatByMeModal = false
      this.getGuideList();
    },
    refreshFile() {
      this.expGuidePage = 1;
      this.searchGuideInput = '';
      this.ispublic = '';
      //              this.shareStatus = 'all'
      this.creatByMeModal = false;
      this.getGuideList();
    },
    searchCreatedByMe(val) {
      this.expGuidePage = 1;
      this.creatByMeModal = val;
      //              this.shareStatus = 'all'
      //              this.searchGuideInput = ''
      this.getGuideList();
    },
    // 导出指导书
    htmlToWord(guideBook) {
      const msg = this.$Message.loading({
        content: '正在导出...',
        duration: 0,
        closable: true
      });
      //使用后台接口执行导出
      let ele = document.createElement('a'); // 创建下载链接
      ele.download = guideBook.guidbookname; //设置下载的名称
      ele.style.display = 'none'; // 隐藏的可下载链接
      ele.href = `/api/self-study/guide/expGuide/exportExpGuideWord/${guideBook.guidbookid}`;
      // 绑定点击时间
      document.body.appendChild(ele);
      ele.click();
      // 然后移除
      document.body.removeChild(ele);
      setTimeout(msg, 3000);
      return;
      let filename = guideBook.guidbookname;
      exportGuide(guideBook.guidbookid)
        .then((data) => {
          // console.log(res)
          if (data.code == 1) {
            let sectionList = data.attribute.datalist;
            let doc = $(`<div id="doc"><h1 style="text-align:center;">${filename}</h1></div>`);
            let content = '';
            sectionList.forEach((section) => {
              content += `<h2>${section.sectionname}</h2>`;
              content += this.escape2Html(section.sectiontext);
            });
            doc.append(content);
            let imgs = doc.find('img');
            let promises = Array();
            for (let i = 0; i < imgs.length; i++) {
              imgs[i].src = imgs[i].src.replace(/Learn\/\//g, 'Learn/');
              //                              let Img = new Image();
              imgs[i].crossOrigin = 'Anonymous';
              //                              Img.src= imgs[i].src;
              let promise = new Promise(function(resolve, reject) {
                imgs[i].onerror = function() {
                  console.log('error');
                  resolve();
                };
                imgs[i].onload = function() {
                  console.log('success');
                  resolve();
                };
              });
              promises.push(promise);
            }
            Promise.all(promises)
              .then(() => {
                //图片全部加载完成，执行导出
                // guideBook.loading = false;
                wordExport(doc, filename);
              })
              .catch((error) => {
                //console.log(error);
              });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 提交按钮
    submitBtn(name) {
      if (this.isCreate) {
        this.creatGuideHandleSubmit(name);
      } else {
        this.modifySubmit(name);
      }
    },
    // 新建
    addGuideModal() {
      this.isCreate = true;
      this.guideTitle = `创建${this.pageBtnTxt}`;
      this.creatGuideFormValidate.name = '';
      this.creatGuideFormValidate.ispublic = '1';
      this.createGuideModal = true;
    },
    creatGuideHandleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let formData = {};
          formData.guidbookname = this.creatGuideFormValidate.name;
          formData.ispublic = parseInt(this.creatGuideFormValidate.ispublic);
          formData.templateid = this.USER_ID;
          formData.createtime = '';
          formData.designer = this.USER_ID;
          formData.createuser = '';
          creatGuide(formData)
            .then((data) => {
              if (data.code == 1) {
                this.createGuideModal = false;
                //this.getGuideList();
                this.refreshFile();
                this.$Message.success('创建成功！');
              } else {
                this.$Message.error({
                  content: data.message,
                  duration: 3
                });
              }
            })
            .catch((err) => {
              this.$Message.error({
                content: err.data.message
              });
            });
        } else {
          this.$Message.error('请完善信息！');
        }
      });
    },
    creatGuideHandleReset(name) {
      this.$refs[name].resetFields();
      
    },
    // 修改
    madifyGuide(row) {
      this.creatGuideHandleReset('creatGuideFormValidate');
      this.isCreate = false;
      this.createGuideModal = true;
      this.guideTitle = '修改指导书';
      this.creatGuideFormValidate.name = this.escape2Html(row.guidbookname).trim();
      this.creatGuideFormValidate.ispublic = row.ispublic + '';
      this.reGuideId = row.guidbookid;
    },
    modifySubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          let formData = {};
          formData.guidbookname = this.creatGuideFormValidate.name;
          formData.ispublic = parseInt(this.creatGuideFormValidate.ispublic);
          modifyGuide(this.reGuideId, formData)
            .then((data) => {
              if (data.code == 1) {
                this.$Message.success('修改成功！');
                this.createGuideModal = false;
                this.getGuideList();
              } else {
                this.$Message.error('修改失败！');
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          this.$Message.error('请完善信息！');
        }
      });
    },
    // 删除
    delGuide(params) {
      if (params.ispublic === '2' || params.ispublic === 2) {
        this.$Message.info({
          content: '没有权限！',
          duration: 3
        });
        return false;
      } else if (params.designer !== this.USER_ID && !this.isRootDesigner) {
        this.$Message.info({
          content: '没有权限！',
          duration: 3
        });
        return false;
      }
      let guideId = params.guidbookid;
      delGuide(guideId)
        .then((data) => {
          if (data.code == 1) {
            this.$Message.success('删除成功！');
            this.getGuideList();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 段落
    goSection(row) {
      let name;
      if (row.templateid == 'markdown') {
        name = 'markdownEdit';
      } else {
        name = 'section';
      }
      sessionStorage.setItem('queryObj', this.queryObj);
      this.$router.push({
        name: name,
        query: {
          page: this.expGuidePage,
          guidbookid: row.guidbookid,
          guidbookname: row.guidbookname,
          creator: row.designer,
          ispublic: row.ispublic
        }
      });
    },
    // 指导书详情
    showBookInfo(row) {
      this.guideName = row.guidbookname;
      if (row.templateid == 'markdown') {
        this.isMd = true;
      } else {
        this.isMd = false;
      }
      this.sectionData = [];
      this.queryList(row.guidbookid);
      this.bookInfoModal = true;
    },
    // 段落列表
    queryList(id) {
      sectionList(id)
        .then((data) => {
          if (data.code == 1) {
            this.sectionData = data.attribute.datalist;
            this.sectionData.forEach((section) => {
              this.querySectionQuestion(section);
            });
            if (this.sectionData.length > 0) {
              this.showSection = true;
              this.showDefImg1 = false;
            } else {
              this.showSection = false;
              this.showDefImg1 = true;
            }
            this.addAddressForImg();
          } else {
            this.$Message.error(data.message);
          }
        })
        .catch((err) => {
          console.log(err);
          this.showSection = false;
          this.showDefImg1 = true;
        });
    },
    querySectionQuestion(section) {
      querySectionQuestion(section.sectionid)
        .then((data) => {
          if (data.code == 1) {
            this.$set(section, 'sectionQuestionList', data.data.items);
          } else {
            this.$set(section, 'sectionQuestionList', []);
          }
        })
        .catch((error) => {
          console.log(error);
          this.$set(section, 'sectionQuestionList', []);
        });
    },
    // 给a标签添加跳转
    addAddressForImg() {
      this.$nextTick(() => {
        let $imgs = $('.main_list a');
        for (let i = 0; i < $imgs.length; i++) {
          $imgs[i].target = '_blank';
        }
      });
    },
    // 测试用
    clickName() {
      // this.$router.push({
      //     name: 'test-markdown',
      // })
    },
    // 计算index
    handleProIndex(key) {
      return (this.expGuidePage - 1) * this.expGuidePageSize + key + 1;
    },
    // 设置可见范围
    setVisibility(val) {
      let obj = {};
      let text = '';
      let color = '';
      if (val === 1 || val === '1') {
        text = '单位';
        color = '#32CD32';
      } else if (val === 0 || val === '0') {
        text = '个人';
        color = '#FFA500';
      } else if (val === 2 || val === '2') {
        text = '系统';
        color = '#4169E1';
      }
      obj.text = text;
      obj.color = color;
      return obj;
    },
    // 设置知否可点击
    setIsClick(item) {
      if (
        item.ispublic === '2' ||
        item.ispublic === 2 ||
        (item.designer !== this.USER_ID && !this.isRootDesigner) ||
        item.expUsed
      ) {
        return { 'pointer-events': 'none' };
      }
    },
    setDownloadIsClick(item) {
      if (!item.existSection) {
        return { 'pointer-events': 'none' };
      }
    },
    setModifyIsClick(item) {
      if (
        item.ispublic === '2' ||
        item.ispublic === 2 ||
        (item.designer !== this.USER_ID && !this.isRootDesigner)
      ) {
        return { 'pointer-events': 'none' };
      }
    },
    setImgSrc(item) {
      if (
        item.ispublic === '2' ||
        item.ispublic === 2 ||
        (item.designer !== this.USER_ID && !this.isRootDesigner)
      ) {
        return require('../../assets/project/modifys.png');
      } else {
        return require('../../assets/project/modifys-h.png');
      }
    },
    setDelImgSrc(item) {
      if (
        item.ispublic === '2' ||
        item.ispublic === 2 ||
        (item.designer !== this.USER_ID && !this.isRootDesigner) ||
        item.expUsed
      ) {
        return require('../../assets/project/delNote-d.png');
      } else {
        return require('../../assets/project/delNote-h.png');
      }
    },
    // 设置是否可以点击段落
    setBtnType(item) {
      if (
        item.ispublic === '2' ||
        item.ispublic === 2 ||
        (item.designer !== this.USER_ID && !this.isRootDesigner)
      ) {
        return true;
      } else {
        return false;
      }
    },
    escape2Html(str) {
      return escape2Html(str);
    },
    //导入指导书
    importGuide() {
      this.importGuideModal = true;
      this.importGuideFormValidate.file = '';
    },
    handleUploadIcon(file) {
      this.speed = 0;
      this.loaded = 0;
      this.progress = 0;
      this.isUpdataing = true;
      this.importGuideFormValidate.file = '';
      this.onlyFileName = file.name + '_' + new Date().getTime();
      if (file) {
        if (file.size > 1024 * 1024) {
          this.fileSize = (Math.round((file.size * 100) / (1024 * 1024)) / 100).toString() + 'MB';
        } else {
          this.fileSize = (Math.round((file.size * 100) / 1024) / 100).toString() + 'KB';
        }
        //验证名称
        if (file.name) {
          let exceededNum = file.name.lastIndexOf('.');
          let exceededStr = file.name
            .substring(exceededNum + 1, file.name.length)
            .trim()
            .toLowerCase();
          let fileName = file.name.substring(0, exceededNum);
          // let reg = /[\\\:：*?？"”<>|;；，,+=]/gi;
          let reg = newValidationRules;
          if (exceededStr && this.formatArr.indexOf(exceededStr) == -1) {
            this.$Message.error({
              content: '不支持当前文件类型',
              duration: 3
            });
          } else if (reg.test(fileName) || fileName.length > 64) {
            this.$Message.error({
              content: newValidationRulesTip('文件名',128),
              duration: 3
            });
          } 
          // else if (file.size > 20480000) {
          //   this.$Message.error({
          //     content: '文件大小不能超过20M',
          //     duration: 3
          //   });
          // } 
          else {
            this.importGuideFormValidate.file = file;
          }
          return false;
        }
      }
    },
    formBtn(name) {
      let _this = this;
      if (!this.importGuideFormValidate.file) {
        _this.$Message.warning({
          content: '请先选择文件！',
          duration: 2
        });
        return;
      }
      this.$refs[name].validate((valid) => {
        if (valid) {
          let formData = new window.FormData();
          formData.append('file', _this.importGuideFormValidate.file);
          let file = {
            name: this.onlyFileName //this.formItem.file.name
          };
          _this.loading = true;
          _this
            .axios({
              method: 'post',
              url: _this.upLoadUrl,
              data: formData,
              headers: {
                'Content-type': 'multipart/form-data'
              },
              timeout:0,
              onUploadProgress: (progressEvent) => {
                //解决上传过程中关闭了modal,再选择文件，会显示上次上传的进度级速度问题
                if (file.name && _this.onlyFileName && file.name != _this.onlyFileName) {
                  return;
                }
                var complete = Math.floor((progressEvent.loaded / progressEvent.total) * 100);
                _this.progress = complete;
                function getspeed() {
                  var aaspeed = Number(progressEvent.loaded - _this.loaded);
                  _this.loaded = progressEvent.loaded;
                  if (aaspeed > 1024 * 1024) {
                    _this.speed =
                      (Math.round((aaspeed * 100) / (1024 * 1024)) / 100).toString() + 'MB/s';
                  } else {
                    _this.speed = (Math.round((aaspeed * 100) / 1024) / 100).toString() + 'KB/s';
                  }
                }
                setInterval(getspeed(), 1000);
              }
            })
            .then((data) => {
              let res = data.data;
              if (res.code == 1) {
                _this.importGuideFormValidate.file = null;
                if (_this.progress === 100) {
                  _this.$Message.success({
                    content: '创建成功！',
                    duration: 2
                  });
                }
                setTimeout(() => {
                  _this.loading = false;
                  this.importGuideModal = false;
                  this.uploadShow = false;
                  this.refreshFile();
                }, 2000);
              } else {
                _this.loading = false;
                this.importGuideFormValidate.file = null;
                this.speed = 0;
                this.loaded = 0;
                this.fileSize = 0;
                this.progress = 0;
                this.uploadShow = false;
                _this.$Message.error({
                  content: res.message,
                  duration: 3
                });
              }
            })
            .catch((err) => {
              console.log(err);
              _this.$Message.error('服务器连接失败！');
              _this.loading = false;
            });
        } else {
          _this.$Message.error('请完善信息！');
        }
      });
    },
    cancelUpload() {
      //关闭上传给出提示
      this.importGuideModal = false;
      //              let _this = this
      //              if(_this.isUpdataing){
      //                  _this.uploadShow = true
      //                  _this.changeModalLoading()
      //              }else{
      //                  this.uploadFileModal = false;
      //              }
    }
  }
};
</script>
<style scoped>
.too {
  position: absolute;
  left: 113px;
  top: -1px;
}
.ios-alert {
  color: orange;
  font-size: 16px;
  cursor: pointer;
}
.openCloseIcon {
  cursor: pointer;
}
.openCloseIcon:hover {
  color: blue;
}
.main_list {
  width: 100%;
  /* overflow: hidden; */
  overflow-x: hidden;
  overflow-y: auto;
  max-height: 700px;
  padding-right: 10px;
}
.main_list .exp {
  width: 100%;
  overflow: hidden;
  display: none;
}
</style>
<style>
.tooltipclass .ivu-poptip-inner {
  background-color: rgba(70, 76, 91, 0.9);
  color: #fff;
}
.tooltipclass.ivu-poptip-popper[x-placement^='top'] .ivu-poptip-arrow:after {
  border-top-color: rgba(70, 76, 91, 0.9);
}
</style>
